from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.course import Course as CourseModel, CourseInDB
from app.schemas.course import Course as CourseSchema, CourseCreate, CourseUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/courses", tags=["courses"])

@router.post("/create", response_model=APIResponse[CourseSchema])
def create_course(course: CourseCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating course with course_code: {course.course_code}")
    
    # 检查课程编码是否已存在
    db_course = db.query(CourseModel).filter(CourseModel.course_code == course.course_code).first()
    if db_course:
        logger.warning(f"Course already registered with course_code: {course.course_code}")
        return error_response(message="Course already registered", code=400)
    
    # 创建新课程
    db_course = CourseModel(
        course_code=course.course_code,
        course_name=course.course_name,
        course_type=course.course_type,
        grade_range=course.grade_range,
        credit=course.credit,
        course_hours=course.course_hours,
        course_desc=course.course_desc,
        status=course.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_course)
    db.commit()
    db.refresh(db_course)
    
    # 转换为Pydantic模型
    course_response = CourseInDB.model_validate(db_course)
    
    logger.info(f"Course created successfully with ID: {db_course.id}")
    return success_response(data=course_response, message="Course created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[CourseSchema]])
def read_courses(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching courses with skip: {skip}, limit: {limit}")
    
    courses = db.query(CourseModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    courses_response = [CourseInDB.model_validate(course) for course in courses]
    total = db.query(CourseModel).count()
    
    logger.info(f"Found {len(courses)} courses")
    return paginated_response(
        items=courses_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{course_id}", response_model=APIResponse[CourseSchema])
def read_course(course_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching course with ID: {course_id}")
    
    db_course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if db_course is None:
        logger.warning(f"Course not found with ID: {course_id}")
        return error_response(message="Course not found", code=404)
    
    # 转换为Pydantic模型
    course_response = CourseInDB.model_validate(db_course)
    
    logger.info(f"Course found with ID: {course_id}")
    return success_response(data=course_response)

@router.put("/{course_id}", response_model=APIResponse[CourseSchema])
def update_course(course_id: int, course: CourseUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating course with ID: {course_id}")
    
    db_course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if db_course is None:
        logger.warning(f"Course not found with ID: {course_id}")
        return error_response(message="Course not found", code=404)
    
    # 更新课程信息
    update_data = course.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_course, key, value)
    
    db_course.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_course)
    
    # 转换为Pydantic模型
    course_response = CourseInDB.model_validate(db_course)
    
    logger.info(f"Course updated successfully with ID: {course_id}")
    return success_response(data=course_response, message="Course updated successfully")

@router.delete("/{course_id}", response_model=APIResponse[None])
def delete_course(course_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting course with ID: {course_id}")
    
    db_course = db.query(CourseModel).filter(CourseModel.id == course_id).first()
    if db_course is None:
        logger.warning(f"Course not found with ID: {course_id}")
        return error_response(message="Course not found", code=404)
    
    db.delete(db_course)
    db.commit()
    
    logger.info(f"Course deleted successfully with ID: {course_id}")
    return success_response(message="Course deleted successfully")
